package org.demo.system.mapper.impl;

import lombok.SneakyThrows;
import org.demo.base.auth.domain.Role;
import org.demo.system.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.util.Arrays;
import java.util.List;

/**
 * @author tomdog
 */
// @Repository
public class RoleMapperImpl implements RoleMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询用户的所有角色
     * @param userId
     * @return
     */
    @Override
    public List<Role> listByUserId(Long userId) {
        List<Role> list = jdbcTemplate.query(
                "select id, role_key, `desc` from t_sys_role " +
                    "where role_key in (select role_key from t_sys_user_role where user_id=?)"
                , this::mapToBean
                , userId
        );
        return list;
    }

    @Override
    public void addRoleForUser(Long userId, String... roleKeys) {
        // 批量插入
        jdbcTemplate.batchUpdate(
                "insert into t_sys_user_role values (?, ?)"
                , Arrays.asList(roleKeys), 2000
                , (ps, argument) -> {
                    ps.setLong(1, userId);
                    ps.setString(2, argument);
                }
        );
    }

    @SneakyThrows
    private Role mapToBean(ResultSet rs, int rowNum) {
        return Role.builder()
                .id(rs.getLong("id"))
                .roleKey(rs.getString("role_key"))
                .desc(rs.getString("desc"))
                .build();
    }
}
